# **装饰器管理**
from collections import defaultdict
from operator import itemgetter
from utils.http_requester import HttpRequester

def group_sort_decorator(func):
    """
    对excel数据按照story分组，order排序的处理
    :param func: read_excel()
    :return: 分组排序后的excel数据
    """
    def wrapper(*args,**kwargs):
        data = func(*args,**kwargs)
        grouped_data = defaultdict(list)

        # 1、遍历了excel读取出来的原始数据，然后进行了分组
        for story in data:
            grouped_data[story['story']].append(story)

        sorted_grouped_data = {story: sorted(item, key=itemgetter("order")) for story, item in grouped_data.items()}

        # 3、把数据结构还原为原始的read_excel()返回的数据结构
        res_data = []
        for value in sorted_grouped_data.values():
            res_data.extend(value)
        return res_data

    return wrapper


def singleton(cls):
    """
    单例模式的装饰器
    :param cls: 需要实现单例模式的类
    :return:
    """
    instance = {}
    def get_instance(*args,**kwargs):
        if cls not in instance:
            instance[cls] = cls(*args,*kwargs)
        return instance[cls]
    return get_instance


def http_request_wrapper(func):
    """
    通过装饰器简化send_http_request的调用逻辑
    :param func: send_http_request
    :return:
    """
    def wrapper(*args,**kwargs):
        data = func(*args,**kwargs)
        return HttpRequester().send_request(**data)
    return wrapper

